# -*- coding: utf-8 -*-
"""
HaaS506 RTU 命令调度模块
提供统一的命令处理和调度功能
"""

import ujson as json
import utime

# System functions
import rtu_config
import rtu_gpio
import rtu_mqtt
import rtu_storage
import rtu_ota
import rtu_time
import rtu_data

# 命令处理器映射
_command_handlers = {}


def init():
    """初始化调度模块"""
    _register_command_handlers()
    print("[DISPATCH] Command dispatch module initialized")
    return True


def _register_command_handlers():
    """注册命令处理器"""
    global _command_handlers

    # 配置相关命令
    _command_handlers["get_config"] = _handle_get_config
    _command_handlers["set_config"] = _handle_set_config
    _command_handlers["remove_config"] = _handle_remove_config
    _command_handlers["save_config"] = _handle_save_config
    _command_handlers["refresh_config"] = _handle_refresh_config

    # 系统相关命令
    _command_handlers["reboot"] = _handle_reboot
    _command_handlers["get_system_info"] = _handle_get_system_info
    _command_handlers["get_status"] = _handle_get_status

    # 继电器控制命令
    _command_handlers["set_relay"] = _handle_set_relay
    _command_handlers["get_relay"] = _handle_get_relay

    # 数据相关命令
    _command_handlers["collect_data"] = _handle_collect_data
    _command_handlers["upload_data"] = _handle_upload_data
    _command_handlers["get_data_stats"] = _handle_get_data_stats

    # OTA相关命令
    _command_handlers["check_update"] = _handle_check_update
    _command_handlers["force_update"] = _handle_force_update
    _command_handlers["ota"] = _handle_ota

    # 时间相关命令
    _command_handlers["sync_time"] = _handle_sync_time
    _command_handlers["get_time"] = _handle_get_time

    # 存储相关命令
    _command_handlers["get_storage_stats"] = _handle_get_storage_stats
    _command_handlers["clear_cache"] = _handle_clear_cache

    # 其他命令
    _command_handlers["version"] = _handle_version
    _command_handlers["get_all_config"] = _handle_get_all_config
    _command_handlers["update_config"] = _handle_update_config
    _command_handlers["list_config"] = _handle_list_config
    _command_handlers["flash_config"] = _handle_flash_config
    _command_handlers["flash_format"] = _handle_flash_format
    _command_handlers["flash_info"] = _handle_flash_info
    _command_handlers["data_info"] = _handle_data_info
    _command_handlers["data_clear"] = _handle_data_clear
    _command_handlers["ping"] = _handle_ping

    # 报警命令
    _command_handlers["get_alarm_status"] = _handle_get_alarm_status
    _command_handlers["get_power_status"] = _handle_get_power_status

    # 调试命令
    _command_handlers["scan_modbus"] = _handle_scan_modbus


def process_command(command_data, source="unknown"):
    """处理命令
    Args:
        command_data: 命令数据
        source: 命令来源 ("ttl", "mqtt", "unknown")
    """
    try:
        if isinstance(command_data, str):
            # 检查字符串大小
            MAX_JSON_SIZE = 4096
            if len(command_data) > MAX_JSON_SIZE:
                print(
                    "[DISPATCH] Command too large: {} bytes".format(len(command_data))
                )
                return {"error": "Command too large"}

            try:
                command = json.loads(command_data)
            except ValueError as e:
                print("[DISPATCH] Invalid JSON: {}".format(e))
                return {"error": "Invalid JSON"}
            except MemoryError:
                print("[DISPATCH] Out of memory parsing JSON")
                return {"error": "Out of memory"}
        else:
            command = command_data

        cmd_type = command.get("command")
        params = command.get("params", {})

        if cmd_type in _command_handlers:
            print("[DISPATCH] Processing command: {} (source: {})".format(cmd_type, source))
            # 将 source 添加到 params 中
            params["_source"] = source
            result = _command_handlers[cmd_type](params)

            return {
                "status": "success",
                "command": cmd_type,
                "result": result,
                "timestamp": utime.time(),
            }
        else:
            return {
                "status": "error",
                "command": cmd_type,
                "message": "Unknown command: {}".format(cmd_type),
                "timestamp": utime.time(),
            }

    except Exception as e:
        print("[DISPATCH] Command processing error: {}".format(e))
        return {"status": "error", "message": str(e), "timestamp": utime.time()}


def _handle_get_config(params):
    """处理获取配置命令"""
    key = params.get("key")
    default = params.get("default")

    if key:
        value = rtu_config.get_config(key, default)
        return {"data": {"key": key, "value": value}}
    else:
        return {"data": rtu_config.get_config()}


def _handle_set_config(params):
    """处理设置配置命令 - 增强版，支持创建新键"""
    key = params.get("key")
    value = params.get("value")

    if key and value is not None:
        # 增强版set_config - 如果键不存在则创建
        try:
            # 先尝试获取当前配置
            current_config = rtu_config.get_config()
            
            # 解析键路径
            keys = key.split('.')
            
            # 使用递归方式设置值，如果中间路径不存在则创建
            def set_nested_value(obj, key_path, value):
                if len(key_path) == 1:
                    obj[key_path[0]] = value
                else:
                    if key_path[0] not in obj:
                        obj[key_path[0]] = {}
                    set_nested_value(obj[key_path[0]], key_path[1:], value)
            
            # 设置新值
            set_nested_value(current_config, keys, value)
            
            # 保存到rtu_config模块的内存配置
            rtu_config._config = current_config
            
            # 如果设置的是device_sn，同时保存到持久化文件
            if key == "device.device_sn":
                # 获取命令来源
                source = params.get("_source", "unknown")
                rtu_config.save_device_sn_persistent(value, source=source)
            
            # 保存到文件
            if rtu_config.save_config():
                print("[DISPATCH] Config key '{}' set to '{}'".format(key, value))
                
                # 如果设置的是 device_sn，需要重启设备以确保 MQTT 订阅地址更新
                if key == "device.device_sn":
                    print(
                        "[DISPATCH] device_sn changed to {}, verifying save...".format(
                            value
                        )
                    )
                    
                    # 验证配置文件是否正确保存
                    verification_success = False
                    for i in range(3):
                        try:
                            # 重新读取配置文件验证
                            with open("/haas/config.json", "r") as f:
                                verify_config = json.load(f)
                            
                            saved_sn = verify_config.get("device", {}).get("device_sn", "")
                            if str(saved_sn) == str(value):
                                print("[DISPATCH] Config file verification passed")
                                
                                # 再验证持久化文件
                                try:
                                    with open("/haas/device_sn.txt", "r") as f:
                                        persistent_sn = f.read().strip()
                                    
                                    if persistent_sn == str(value):
                                        print("[DISPATCH] Persistent file verification passed")
                                        verification_success = True
                                        break
                                    else:
                                        print("[DISPATCH] Persistent file mismatch: {} vs {}".format(persistent_sn, value))
                                except Exception as e:
                                    print("[DISPATCH] Failed to verify persistent file: {}".format(e))
                            else:
                                print("[DISPATCH] Config file mismatch: {} vs {}".format(saved_sn, value))
                                
                        except Exception as e:
                            print("[DISPATCH] Verification attempt {} failed: {}".format(i + 1, e))
                        
                        if i < 2:
                            utime.sleep(1)  # 等待1秒再重试
                    
                    if verification_success:
                        print("[DISPATCH] device_sn saved successfully, rebooting in 3 seconds...")
                        # 先返回成功响应，再重启
                        response = {
                            "data": {
                                "key": key, 
                                "value": value, 
                                "message": "device_sn updated successfully, device will reboot in 3 seconds"
                            }
                        }
                        # 如果是TTL调用，立即发送响应
                        try:
                            import rtu_ttl
                            rtu_ttl._send_response(response)
                        except:
                            pass
                        
                        # 延迟3秒后重启，确保文件系统同步
                        utime.sleep(3)
                        import rtu_system
                        rtu_system.restart(0)
                    else:
                        # 即使验证失败，config.json可能已经保存成功
                        # 检查是否实际保存成功
                        actual_saved = False
                        try:
                            with open("/haas/config.json", "r") as f:
                                check_config = json.load(f)
                            if str(check_config.get("device", {}).get("device_sn", "")) == str(value):
                                actual_saved = True
                        except:
                            pass
                        
                        if actual_saved:
                            print("[DISPATCH] WARNING: Persistent file verification failed, but config.json saved successfully")
                            print("[DISPATCH] device_sn will take effect after manual reboot")
                            return {
                                "data": {
                                    "key": key,
                                    "value": value,
                                    "message": "device_sn saved to config.json, but persistent file failed. Manual reboot required.",
                                    "warning": "persistent_file_failed"
                                }
                            }
                        else:
                            print("[DISPATCH] ERROR: device_sn save verification failed!")
                            raise Exception("Failed to verify device_sn save")
                
                return {
                    "data": {"key": key, "value": value, "message": "Configuration updated"}
                }
            else:
                raise Exception("Failed to save configuration")
        except Exception as e:
            print("[DISPATCH] Error setting config: {}".format(e))
            raise Exception("Failed to update configuration: {}".format(e))
    else:
        raise Exception("Key and value are required")


def _handle_remove_config(params):
    """处理删除配置键命令"""
    key = params.get("key")
    
    if not key:
        raise Exception("Key is required")
    
    try:
        # 获取当前配置
        current_config = rtu_config.get_config()
        
        # 解析键路径
        keys = key.split('.')
        
        # 使用递归方式删除键
        def remove_nested_key(obj, key_path):
            if len(key_path) == 1:
                if key_path[0] in obj:
                    del obj[key_path[0]]
                    return True
                else:
                    return False
            else:
                if key_path[0] in obj and isinstance(obj[key_path[0]], dict):
                    return remove_nested_key(obj[key_path[0]], key_path[1:])
                else:
                    return False
        
        # 删除键
        if remove_nested_key(current_config, keys):
            # 保存到rtu_config模块的内存配置
            rtu_config._config = current_config
            
            # 保存到文件
            if rtu_config.save_config():
                print("[DISPATCH] Config key '{}' removed successfully".format(key))
                return {
                    "data": {"key": key, "message": "Configuration key removed"}
                }
            else:
                raise Exception("Failed to save configuration after removal")
        else:
            return {
                "data": {"key": key, "message": "Configuration key not found"}
            }
            
    except Exception as e:
        print("[DISPATCH] Error removing config: {}".format(e))
        raise Exception("Failed to remove configuration: {}".format(e))


def _handle_save_config(params):
    """处理保存配置命令"""
    if rtu_config.save_config():
        return {"message": "Configuration saved"}
    else:
        raise Exception("Failed to save configuration")


def _handle_refresh_config(params):
    """处理刷新配置命令 - 从/luadb/config.json更新到/haas/config.json，保持device_sn不变"""
    try:
        import uos

        print("[DISPATCH] Refreshing configuration from /luadb/config.json...")

        # 1. 检查/luadb/config.json是否存在
        try:
            uos.stat("/luadb/config.json")
        except OSError:
            return {"status": "error", "message": "/luadb/config.json not found"}

        # 2. 读取当前/haas/config.json中的device_sn
        original_device_sn = "unknown"
        original_config = {}

        try:
            with open("/haas/config.json", "r") as f:
                original_config = json.load(f)
            original_device_sn = original_config.get("device", {}).get(
                "device_sn", "unknown"
            )
            print("[DISPATCH] Current device_sn: {}".format(original_device_sn))
        except Exception as e:
            print("[DISPATCH] Failed to read current config: {}".format(e))
            # 如果读取失败，使用配置模块中的值
            original_device_sn = rtu_config.get_device_sn()
            print(
                "[DISPATCH] Using device_sn from config module: {}".format(
                    original_device_sn
                )
            )

        # 2.5 如果device_sn仍然是默认值，尝试从持久化文件读取
        if (
            original_device_sn == "unknown"
            or original_device_sn == 10000
            or original_device_sn == "10000"
        ):
            try:
                with open("/haas/device_sn.txt", "r") as f:
                    saved_sn = f.read().strip()
                if saved_sn and saved_sn != "10000":
                    original_device_sn = saved_sn
                    print(
                        "[DISPATCH] Recovered device_sn from persistent file: {}".format(
                            original_device_sn
                        )
                    )
            except:
                pass

        # 3. 读取新的/luadb/config.json
        new_config = {}
        try:
            with open("/luadb/config.json", "r") as f:
                new_config = json.load(f)
            print("[DISPATCH] Successfully read /luadb/config.json")
        except Exception as e:
            return {
                "status": "error",
                "message": "Failed to read /luadb/config.json: {}".format(e),
            }

        # 4. 保持原始device_sn不变
        if "device" not in new_config:
            new_config["device"] = {}
        new_config["device"]["device_sn"] = original_device_sn

        print("[DISPATCH] Preserving device_sn: {}".format(original_device_sn))

        # 4.5 保存device_sn到持久化文件
        try:
            with open("/haas/device_sn.txt", "w") as f:
                f.write(str(original_device_sn))
            print("[DISPATCH] Saved device_sn to persistent file")
        except Exception as e:
            print(
                "[DISPATCH] Failed to save device_sn to persistent file: {}".format(e)
            )

        # 5. 备份原配置文件
        try:
            uos.rename("/haas/config.json", "/haas/config.json.bak")
            print("[DISPATCH] Backed up original config to config.json.bak")
        except Exception as e:
            print("[DISPATCH] Config backup failed: {}".format(e))

        # 6. 保存合并后的配置到/haas/config.json
        try:
            with open("/haas/config.json", "w") as f:
                json.dump(new_config, f)
            print("[DISPATCH] Config updated successfully")

            # 7. 删除/luadb/config.json避免重复处理
            try:
                uos.remove("/luadb/config.json")
                print("[DISPATCH] Removed /luadb/config.json after merge")
            except Exception as e:
                print(
                    "[DISPATCH] Note: /luadb/config.json removal failed: {}".format(e)
                )

            # 8. 重新加载配置
            rtu_config.load_config()

            return {
                "status": "success",
                "message": "Configuration refreshed successfully",
                "data": {
                    "device_sn": original_device_sn,
                    "version": new_config.get("system", {}).get("version", "unknown"),
                },
            }

        except Exception as e:
            print("[DISPATCH] Failed to save updated config: {}".format(e))
            # 尝试恢复备份
            try:
                uos.rename("/haas/config.json.bak", "/haas/config.json")
                print("[DISPATCH] Restored config from backup")
            except Exception as restore_e:
                print(
                    "[DISPATCH] Failed to restore config backup: {}".format(restore_e)
                )
            return {"status": "error", "message": "Failed to save config: {}".format(e)}

    except Exception as e:
        print("[DISPATCH] Refresh config error: {}".format(e))
        return {"status": "error", "message": "Refresh config failed: {}".format(e)}


def _handle_reboot(params):
    """处理重启命令"""
    delay = params.get("delay", 3)

    def delayed_reboot():
        # 使用系统模块的重启功能（会保存时间戳）
        import rtu_system

        rtu_system.restart(delay)

    # 启动延时重启
    import _thread

    _thread.start_new_thread(delayed_reboot, ())

    return {
        "message": "System will reboot in {} seconds".format(delay),
        "status": "success",
        "data": {"delay": delay},
    }


def _handle_get_system_info(params):
    """处理获取系统信息命令"""
    import gc
    import rtu_system

    # 获取系统模块信息
    sys_info = rtu_system.get_system_info()

    return {
        "status": "success",
        "message": "System info retrieved successfully",
        "data": {
            "device_sn": rtu_config.get_device_sn(),
            "version": rtu_config.get_config("system.version", "2.0.0"),
            "hardware": rtu_config.get_config("device.hardware", "HaaS506-HD1"),
            "memory_free": gc.mem_free(),
            "memory_alloc": gc.mem_alloc(),
            "network_connected": rtu_config.g_network_ready,
            "mqtt_connected": rtu_config.g_mqtt_connected,
            "time_synced": rtu_config.g_time_synced,
            "system_status": rtu_config.g_system_status,
            "reboot_count": sys_info.get("reboot_count", 0) if sys_info else 0,
            "last_timestamp": sys_info.get("last_timestamp", 0) if sys_info else 0,
            "cached_timestamp": sys_info.get("cached_timestamp", 0) if sys_info else 0,
            "time_normal": sys_info.get("time_normal", False) if sys_info else False,
        }
    }


def _handle_get_status(params):
    """处理获取状态命令"""
    return _handle_get_system_info(params)


def _handle_set_relay(params):
    """处理设置继电器命令"""
    relay_id = params.get("relay_id")
    state = params.get("state")

    if relay_id is not None and state is not None:
        if rtu_gpio.set_relay(relay_id, state):
            return {
                "data": {
                    "relay_id": relay_id,
                    "state": state,
                    "message": "Relay state updated",
                }
            }
        else:
            raise Exception("Failed to update relay state")
    else:
        raise Exception("relay_id and state are required")


def _handle_get_relay(params):
    """处理获取继电器状态命令"""
    relay_id = params.get("relay_id")

    if relay_id is not None:
        state = rtu_gpio.get_relay_state(relay_id)
        return {"data": {"relay_id": relay_id, "state": state}}
    else:
        # 返回所有继电器状态
        return {
            "status": "success",
            "message": "All relay states retrieved successfully",
            "data": {
                "relay1": rtu_gpio.get_relay_state(1),
                "relay2": rtu_gpio.get_relay_state(2),
            }
        }


def _handle_collect_data(params):
    """处理数据采集命令"""
    data = rtu_data.collect_data()
    if data:
        return {"data": data, "message": "Data collected successfully"}
    else:
        raise Exception("Data collection failed")


def _handle_upload_data(params):
    """处理数据上传命令"""
    if rtu_data.upload_data():
        return {"message": "Data uploaded successfully"}
    else:
        raise Exception("Data upload failed")


def _handle_get_data_stats(params):
    """处理获取数据统计命令"""
    stats = rtu_data.get_data_statistics()
    if stats:
        return {"statistics": stats}
    else:
        raise Exception("Failed to get data statistics")


def _handle_check_update(params):
    """处理检查更新命令"""
    if rtu_ota.check_update():
        return {"message": "Update check completed"}
    else:
        return {"message": "No update available"}


def _handle_force_update(params):
    """处理强制更新命令"""
    if rtu_ota.force_update_check():
        return {"message": "Force update check completed"}
    else:
        return {"message": "No update available"}


def _handle_ota(params):
    """处理OTA命令"""
    action = params.get("action", "check_update")

    if action == "check_update" or action == "check":
        if rtu_ota.manual_trigger():
            return {"message": "OTA update check triggered"}
        else:
            return {"message": "OTA check completed, no update available"}
    elif action == "status":
        status = rtu_ota.get_ota_status()
        return {"data": status}
    else:
        # 默认执行检查更新
        if rtu_ota.manual_trigger():
            return {"message": "OTA update check triggered"}
        else:
            return {"message": "OTA check completed, no update available"}


def _handle_sync_time(params):
    """处理时间同步命令"""
    if rtu_time.sync_time():
        return {"message": "Time synchronized successfully"}
    else:
        raise Exception("Time synchronization failed")


def _handle_get_time(params):
    """处理获取时间命令"""
    return {
        "data": {
            "current_time": utime.time(),
            "formatted_time": rtu_time.get_current_time(),
            "timestamp": utime.time(),
            "time_synced": rtu_config.g_time_synced,
            "time_status": rtu_time.get_time_status(),
        }
    }


def _handle_get_storage_stats(params):
    """处理获取存储统计命令"""
    stats = rtu_storage.get_storage_stats()
    if stats:
        return {"data": stats}
    else:
        raise Exception("Failed to get storage statistics")


def _handle_clear_cache(params):
    """处理清空缓存命令"""
    if rtu_storage.clear_cache():
        return {"data": {"success": True, "message": "Cache cleared successfully"}}
    else:
        raise Exception("Failed to clear cache")


def _handle_version(params):
    """处理版本查询命令"""
    return {
        "data": {
            "version": rtu_config.get_config("system.version", "2.0.0"),
            "device_sn": rtu_config.get_device_sn(),
            "timestamp": utime.time(),
        }
    }


def _handle_get_all_config(params):
    """处理获取所有配置命令"""
    all_config = rtu_config.get_config()
    return {"data": all_config}


def _handle_update_config(params):
    """处理批量更新配置命令"""
    updated_count = 0
    errors = []

    for key, value in params.items():
        try:
            if rtu_config.set_config(key, value):
                updated_count += 1
            else:
                errors.append("Failed to set {}".format(key))
        except Exception as e:
            errors.append("Error setting {}: {}".format(key, str(e)))

    if errors:
        return {
            "data": {"updated_count": updated_count, "errors": errors},
            "message": "Some configs updated with errors",
        }
    else:
        return {
            "data": {"updated_count": updated_count},
            "message": "All configs updated successfully",
        }


def _handle_list_config(params):
    """处理列出配置键命令"""
    # 获取所有配置的键
    all_config = rtu_config.get_config()
    keys = []

    def extract_keys(obj, prefix=""):
        if isinstance(obj, dict):
            for k, v in obj.items():
                full_key = "{}.{}".format(prefix, k) if prefix else k
                if isinstance(v, dict):
                    extract_keys(v, full_key)
                else:
                    keys.append(full_key)

    extract_keys(all_config)

    return {"data": {"supported_keys": keys, "total": len(keys)}}


def _handle_flash_config(params):
    """处理保存配置到Flash命令"""
    if rtu_config.save_config():
        return {"data": {"success": True, "message": "Configuration saved to flash"}}
    else:
        raise Exception("Failed to save configuration to flash")


def _handle_flash_format(params):
    """处理格式化Flash命令"""
    try:
        import uos

        result = uos.formatflash()
        return {
            "data": {
                "success": True,
                "result": result,
                "message": "Flash formatted successfully",
            }
        }
    except Exception as e:
        raise Exception("Flash format failed: {}".format(str(e)))


def _handle_flash_info(params):
    """处理获取Flash信息命令"""
    try:
        import uos

        flash_info = uos.flashinfo()
        return {"data": flash_info}
    except Exception as e:
        raise Exception("Failed to get flash info: {}".format(str(e)))


def _handle_data_info(params):
    """处理获取数据信息命令"""
    stats = rtu_data.get_data_statistics()
    storage_stats = rtu_storage.get_storage_stats()

    return {
        "data": {
            "buffer_count": stats.get("buffer_count", 0) if stats else 0,
            "cache_count": stats.get("cache_count", 0) if stats else 0,
            "total_pending": stats.get("total_pending", 0) if stats else 0,
            "storage_stats": storage_stats,
        }
    }


def _handle_data_clear(params):
    """处理清空数据命令"""
    if rtu_data.clear_all_data():
        stats = rtu_data.get_data_statistics()
        return {
            "data": {
                "success": True,
                "message": "All data cleared",
                "remaining_count": stats.get("total_pending", 0) if stats else 0,
            }
        }
    else:
        raise Exception("Failed to clear all data")


def _handle_ping(params):
    """处理ping命令"""
    return {
        "data": {
            "status": "pong",
            "timestamp": utime.time(),
            "device_sn": rtu_config.get_device_sn(),
        }
    }


def _handle_get_alarm_status(params):
    """处理获取报警状态命令"""
    alarm_status = rtu_gpio.get_alarm_status()
    return {"data": alarm_status}


def _handle_get_power_status(params):
    """处理获取电源状态命令"""
    power_status = rtu_gpio.get_power_status()
    return {"data": power_status}


def _handle_scan_modbus(params):
    """处理扫描Modbus寄存器命令"""
    import rtu_modbus

    # 获取扫描参数
    start_addr = params.get("start", 0x0000)
    end_addr = params.get("end", 0x0100)
    count = params.get("count", 6)

    # 执行扫描
    print("[DISPATCH] Starting Modbus register scan...")
    rtu_modbus.scan_power_meter_registers(start_addr, end_addr, count)

    return {
        "status": "success",
        "message": "Modbus scan completed, check device logs for results",
        "data": {
            "start_address": "0x{:04X}".format(start_addr),
            "end_address": "0x{:04X}".format(end_addr),
            "register_count": count,
        },
    }


def get_supported_commands():
    """获取支持的命令列表"""
    return {
        "supported_commands": list(_command_handlers.keys()),
        "total_commands": len(_command_handlers),
    }


def process_mqtt_command(message):
    """处理MQTT命令"""
    try:
        print("[DISPATCH] Processing MQTT command: {}".format(message))

        # MQTT消息可能包含不同的命令格式
        if "action" in message:
            # 旧格式兼容
            print(
                "[DISPATCH] Legacy action format detected: {}".format(
                    message.get("action")
                )
            )
            result = _process_legacy_action(message)
        elif "command" in message:
            # 新格式
            print(
                "[DISPATCH] Standard command format detected: {}".format(
                    message.get("command")
                )
            )
            result = process_command(message, source="mqtt")
        else:
            print("[DISPATCH] Unknown command format")
            result = {
                "status": "error",
                "message": "Unknown command format",
                "timestamp": utime.time(),
            }

        # 发送命令执行结果
        if rtu_config.g_mqtt_connected:
            rtu_mqtt.publish_status(result)

        return result

    except Exception as e:
        print("[DISPATCH] MQTT command error: {}".format(e))
        return {"status": "error", "message": str(e), "timestamp": utime.time()}


def _process_legacy_action(command):
    """处理旧版MQTT命令格式"""
    action = command.get("action")

    # 直接使用action作为command名称
    return process_command({"command": action, "params": command.get("params", {})}, source="mqtt")


def process_ttl_command(command_str):
    """处理TTL命令"""
    try:
        # 检查命令大小
        MAX_JSON_SIZE = 4096
        if len(command_str) > MAX_JSON_SIZE:
            print("[DISPATCH] TTL command too large: {} bytes".format(len(command_str)))
            return {"error": "Command too large"}

        try:
            command = json.loads(command_str)
        except ValueError as e:
            print("[DISPATCH] Invalid TTL JSON: {}".format(e))
            return {"error": "Invalid JSON"}
        except MemoryError:
            print("[DISPATCH] Out of memory parsing TTL JSON")
            return {"error": "Out of memory"}

        # 兼容旧的TTL命令格式
        if "action" in command:
            return _process_legacy_ttl_command(command)
        else:
            return process_command(command, source="ttl")

    except Exception as e:
        print("[DISPATCH] TTL command error: {}".format(e))
        return {"status": "error", "message": str(e), "timestamp": utime.time()}


def _process_legacy_ttl_command(command):
    """处理旧版TTL命令格式"""
    action = command.get("action")

    # 特殊处理的命令
    if action == "get":
        return process_command(
            {"command": "get_config", "params": {"key": command.get("key")}}, source="ttl"
        )
    elif action == "set":
        return process_command(
            {
                "command": "set_config",
                "params": {"key": command.get("key"), "value": command.get("value")},
            }, source="ttl"
        )
    elif action == "list":
        return get_supported_commands()
    elif action == "status":
        return process_command({"command": "get_status", "params": {}}, source="ttl")
    elif action == "time":
        return process_command({"command": "get_time", "params": {}}, source="ttl")
    elif action == "time_sync":
        return process_command({"command": "sync_time", "params": {}}, source="ttl")
    elif action == "system_info":
        return process_command({"command": "get_system_info", "params": {}}, source="ttl")
    else:
        # 其他命令直接使用action作为command名称
        return process_command({"command": action, "params": command.get("params", {})}, source="ttl")


def test_dispatch():
    """测试调度功能"""
    print("[DISPATCH] Testing command dispatch...")

    # 测试支持的命令
    supported = get_supported_commands()
    print("[DISPATCH] Supported commands: {}".format(supported["total_commands"]))

    # 测试基本命令
    test_commands = [
        {"command": "get_system_info", "params": {}},
        {"command": "get_status", "params": {}},
        {"command": "get_config", "params": {"key": "device.device_sn"}},
    ]

    for cmd in test_commands:
        result = process_command(cmd)
        print(
            "[DISPATCH] Test command '{}': {}".format(cmd["command"], result["status"])
        )

    print("[DISPATCH] Dispatch test completed")
